package sample.com.imagecompress;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import sample.com.imagecompress.util.ImageCompress;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_compress;

    private EditText et_size,et_height,et_width;

    private TextView tv_photoInfo;
    private TextView tv_compressInfo;

    private TextView tv_takePhoto;
    private TextView tv_pickPhoto;
    private TextView tv_sourcePreview;


    //压缩及预览按钮定义
    private TextView tv_sampleCompress;
    private TextView tv_samplePreview;
    private TextView tv_sampleInfo;

    private TextView tv_zoomCompress;
    private TextView tv_zoomPreview;
    private TextView tv_zoomInfo;

    private TextView tv_fixedCompress;
    private TextView tv_fixedPreview;
    private TextView tv_fixedInfo;

    // 照片路径
    private Map<String, String> paths = new HashMap<>();
    public static final String IMAGE_PATH = "IMAGE_PATH";
    public static final String SAMPLE_IMAGE_PATH = "SAMPLE_IMAGE_PATH";
    public static final String ZOOM_IMAGE_PATH = "ZOOM_IMAGE_PATH";
    public static final String FIXED_IMAGE_PATH = "FIXED_IMAGE_PATH";


    private String sdCardPath = Environment.getExternalStorageDirectory().getPath();
    private String photoPath;
    private String photoPathTemp;
    private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");

    private static final int REQUEST_TAKE_PHOTO = 10000;
    private static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 10001;
    private static final int REQUEST_PICK_PHOTO = 10002;

    private static final String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

    int size = 60, width = 480, height = 800;
    String watermaker = "收费员:张三shou123\r\n泊位号:230001\r\n2023-01-01 08:08:08";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        this.setTitle(this.getTitle() + "_" + getPosChannel(this.getApplication()));
    }

    void initView() {

        et_size = (EditText) findViewById(R.id.et_size);
        et_width = (EditText) findViewById(R.id.et_width);
        et_height = (EditText) findViewById(R.id.et_height);

        tv_takePhoto = (TextView) findViewById(R.id.tv_takePhoto);
        tv_pickPhoto = (TextView) findViewById(R.id.tv_pickPhoto);
        tv_sourcePreview = (TextView) findViewById(R.id.tv_sourcePreview);

        btn_compress = (Button) findViewById(R.id.btn_compress);

        tv_photoInfo = (TextView) findViewById(R.id.tv_photoInfo);
        tv_compressInfo = (TextView) findViewById(R.id.tv_compressInfo);

        tv_sampleCompress = (TextView) findViewById(R.id.tv_sampleCompress);
        tv_samplePreview = (TextView) findViewById(R.id.tv_samplePreview);
        tv_sampleInfo = (TextView) findViewById(R.id.tv_sampleInfo);

        tv_zoomCompress = (TextView) findViewById(R.id.tv_zoomCompress);
        tv_zoomPreview = (TextView) findViewById(R.id.tv_zoomPreview);
        tv_zoomInfo = (TextView) findViewById(R.id.tv_zoomInfo);

        tv_fixedCompress = (TextView) findViewById(R.id.tv_fixedCompress);
        tv_fixedPreview = (TextView) findViewById(R.id.tv_fixedPreview);
        tv_fixedInfo = (TextView) findViewById(R.id.tv_fixedInfo);

        tv_takePhoto.setOnClickListener(this);
        tv_pickPhoto.setOnClickListener(this);
        tv_sourcePreview.setOnClickListener(this);

        btn_compress.setOnClickListener(this);

        tv_sampleCompress.setOnClickListener(this);
        tv_samplePreview.setOnClickListener(this);

        tv_zoomCompress.setOnClickListener(this);
        tv_zoomPreview.setOnClickListener(this);

        tv_fixedCompress.setOnClickListener(this);
        tv_fixedPreview.setOnClickListener(this);

    }

    long timestamp = 0;
    @Override
    public void onClick(View v) {

        try {
            size = Integer.parseInt(et_size.getText().toString());
            width = Integer.parseInt(et_width.getText().toString());
            height = Integer.parseInt(et_height.getText().toString());
            if (size <= 0) {
                Toast.makeText(MainActivity.this, "照片大小不能小于0", Toast.LENGTH_SHORT).show();
                return;
            }
            if (width <= 0 || height <= 0) {
                Toast.makeText(MainActivity.this, "照片宽或高不能小于0", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "输入参数初始化失败", Toast.LENGTH_SHORT).show();
            return;
        }

        switch (v.getId()) {
            case R.id.tv_takePhoto:
                photoPathTemp = photoPath;
                photoPath = sdCardPath + File.separator + format.format((new Date())) + ".jpg";
                showCameraAction();
                break;
            case R.id.tv_pickPhoto:
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_PICK_PHOTO);
                break;
            case R.id.tv_sourcePreview:
                if (photoPath == null) {
                    Toast.makeText(MainActivity.this, "源图片路径不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                previewImage(photoPath);
                break;
            case R.id.tv_sampleCompress:
                timestamp = System.currentTimeMillis();
                Bitmap sampleBitmap = ImageCompress.sampleImage(photoPath, width, height);
                File sampleFile = new File(photoPath + "." + size + "." + timestamp + ".sample.jpg");//将要保存图片的路径

                ImageCompress.saveImage(sampleBitmap, sampleFile, 100);
                File watermarkFile = new File(photoPath + "." + size + "." + timestamp + ".water" + ".sample.jpg");//将要保存图片的路径
                paths.put(SAMPLE_IMAGE_PATH,watermarkFile.toString());
                Bitmap waterAfter = ImageCompress.withWatermark(sampleBitmap, watermaker);
                ImageCompress.compressImage(waterAfter, watermarkFile, size);

                String compressFixInfo = "";
                compressFixInfo += "compressPath = " + watermarkFile.getPath() + "\r\n";
                if (watermarkFile.exists()) {
                    compressFixInfo += "size = " + getFileSize(watermarkFile.length()) + "\r\n";
                }
                tv_sampleInfo.setText(tv_sampleInfo.getText() + "\r\n" + compressFixInfo);
                Toast.makeText(MainActivity.this, "已采样压缩[" + watermarkFile + "]", Toast.LENGTH_LONG).show();
                break;
            case R.id.tv_samplePreview:
                String filePath = paths.get(SAMPLE_IMAGE_PATH);
                previewImage(filePath);
                break;
            case R.id.tv_zoomCompress:
                timestamp = System.currentTimeMillis();
                Bitmap zoomBitmap = ImageCompress.ratioImage(photoPath, width, height);
                File zoomFile = new File(photoPath + "." + size + "." + timestamp + ".zoom.jpg");//将要保存图片的路径

                ImageCompress.saveImage(zoomBitmap, zoomFile, 100);
                watermarkFile = new File(photoPath + "." + size + "." + timestamp + ".water" + ".zoom.jpg");//将要保存图片的路径
                paths.put(ZOOM_IMAGE_PATH,watermarkFile.toString());
                waterAfter = ImageCompress.withWatermark(zoomBitmap, watermaker);
                ImageCompress.compressImage(waterAfter, watermarkFile, size);

                compressFixInfo = "";
                compressFixInfo += "compressPath = " + watermarkFile.getPath() + "\r\n";
                if (watermarkFile.exists()) {
                    compressFixInfo += "size = " + getFileSize(watermarkFile.length()) + "\r\n";
                }
                tv_zoomInfo.setText(tv_zoomInfo.getText() + "\r\n" + compressFixInfo);
                Toast.makeText(MainActivity.this, "已缩放压缩[" + watermarkFile + "]", Toast.LENGTH_LONG).show();
                break;
            case R.id.tv_zoomPreview:
                filePath = paths.get(ZOOM_IMAGE_PATH);
                previewImage(filePath);
                break;
            case R.id.tv_fixedCompress:
                timestamp = System.currentTimeMillis();
                sampleBitmap = ImageCompress.sampleImage(photoPath, width, height);
                Bitmap fixedBitmap = ImageCompress.fixedImage(sampleBitmap, width, height);
                File fixedFile = new File(photoPath + "." + size + "." + timestamp + ".fixed.jpg");//将要保存图片的路径

                ImageCompress.saveImage(fixedBitmap, fixedFile, 100);
                watermarkFile = new File(photoPath + "." + size + "." + timestamp + ".water" + ".fixed.jpg");//将要保存图片的路径
                paths.put(FIXED_IMAGE_PATH,watermarkFile.toString());
                waterAfter = ImageCompress.withWatermark(fixedBitmap, watermaker);
                ImageCompress.compressImage(waterAfter, watermarkFile, size);

                compressFixInfo = "";
                compressFixInfo += "compressPath = " + watermarkFile.getPath() + "\r\n";
                if (watermarkFile.exists()) {
                    compressFixInfo += "size = " + getFileSize(watermarkFile.length()) + "\r\n";
                }
                tv_fixedInfo.setText(tv_fixedInfo.getText() + "\r\n" + compressFixInfo);
                Toast.makeText(MainActivity.this, "已固定压缩[" + watermarkFile + "]", Toast.LENGTH_LONG).show();
                break;
            case R.id.tv_fixedPreview:
                filePath = paths.get(FIXED_IMAGE_PATH);
                previewImage(filePath);
                break;
        }
    }

    private void previewImage(String filePath) {
        if (filePath == null) {
            Toast.makeText(MainActivity.this, "预览图片不存在！", Toast.LENGTH_SHORT).show();
            return;
        }

        File file = new File(filePath);
        if (file == null || !file.exists()) {
            Toast.makeText(MainActivity.this, "预览图片不存在！", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(MainActivity.this, PhotoViewActivity.class);
        Uri uri;
        // 适配7.0代码
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this, this.getApplication().getPackageName() + ".provider", file); //Uri.fromFile(new File(photoPath));
        } else {
            uri = Uri.fromFile(file);//new File(photoPath)
        }//为拍摄的图片指定一个存储的路径
        intent.putExtra("PHOTO_PATH", uri);
        startActivity(intent);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 是否拍照请求
        if (requestCode == REQUEST_TAKE_PHOTO) {
            if (resultCode == RESULT_OK) {
                String photoInfo = "";
                photoInfo += "photoPath = " + photoPath + "\r\n";
                File file = new File(photoPath);
                if (file.exists()) {
                    photoInfo += "size = " + getFileSize(file.length()) + "\r\n";
                }
                tv_photoInfo.setText(photoInfo);
            } else {
                Toast.makeText(MainActivity.this, "拍照取消", Toast.LENGTH_SHORT).show();
                // 拍照取消，还原上次的路径
                photoPath = photoPathTemp;
            }
        } if (requestCode == REQUEST_PICK_PHOTO) {
            if (resultCode == RESULT_OK) {//resultcode是setResult里面设置的code值
                try {
                    Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    photoPath = cursor.getString(columnIndex);  //获取照片路径
                    cursor.close();

                    File photoFile = new File(photoPath);
                    displayPhotoInfo(photoFile);

                    // Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
                    // iv_photo.setImageBitmap(bitmap);
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "照片选取异常", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }else {
                Toast.makeText(MainActivity.this, "取消选取", Toast.LENGTH_SHORT).show();
                // 拍照取消，还原上次的路径
                photoPath = photoPathTemp;
            }
        }

    }

    public void displayPhotoInfo(File file) {
        if (file.exists()) {
            BitmapFactory.Options bmpOptions = ImageCompress.getBmpOptions(file.toString());
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("文件大小：" + getFileSize(file.length())).append("\r\n");
            stringBuffer.append("分辨率(宽x高)：" + bmpOptions.outWidth +"x"+ bmpOptions.outHeight).append("\r\n");

            BitmapFactory.Options options2 = new BitmapFactory.Options();
            options2.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap bitmap = BitmapFactory.decodeFile(file.toString(), options2);
            stringBuffer.append("照片大小：" + getFileSize(bitmap.getByteCount())).append("\r\n");
            stringBuffer.append("分辨率(宽x高)：" + bitmap.getWidth() + "x" + bitmap.getHeight()).append("\r\n");

            tv_photoInfo.setText(stringBuffer.toString());

        } else {
            Toast.makeText(MainActivity.this, "照片不存在[" + file + "]", Toast.LENGTH_LONG).show();
        }
    }

    public static String getFileSize(long fileSize) {

        String size = "N/A";
        DecimalFormat df = new DecimalFormat("#.00");
        if (fileSize < 1024) {
            size = df.format((double) fileSize) + "B";
        } else if (fileSize < 1048576) {
            size = df.format((double) fileSize / 1024) + "KB";
        } else if (fileSize < 1073741824) {
            size = df.format((double) fileSize / 1048576) + "MB";
        } else {
            size = df.format((double) fileSize / 1073741824) + "GB";
        }
        return size;
    }

    private void showCameraAction() {

        if (checkPermissionAllGranted(permissions)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            Uri uri;
            // 适配7.0代码
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, this.getApplication().getPackageName() + ".provider", new File(photoPath)); //Uri.fromFile(new File(photoPath));
            } else {
                uri = Uri.fromFile(new File(photoPath));
            }//为拍摄的图片指定一个存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_TAKE_PHOTO);
        } else {
            ActivityCompat.requestPermissions(this, permissions, REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
        }
    }


    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有授予，直接返回false
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_STORAGE_WRITE_ACCESS_PERMISSION) {
            boolean isAllGranted = true;

            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (isAllGranted) {
                //
                showCameraAction();
            } else {
                openAppDetails();
            }
        }
    }

    /**
     * 打开 APP 的详情设置
     */
    private void openAppDetails() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("应用需要必须的权限，请到 “应用信息 -> 权限” 中授予！");
        builder.setPositiveButton("手动授权", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setData(Uri.parse("package:" + getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 获取POS渠道名
     *
     * @param context 此处习惯性的设置为activity，实际上context就可以
     * @return 如果没有获取成功，那么返回值为空
     */
    public static String getPosChannel(Context context) {
        if (context == null) {
            return null;
        }
        String channelName = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo，因为POS设置的meta-data是在application标签中
                ApplicationInfo applicationInfo = packageManager.
                        getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        //这里的UMENG_CHANNEL要与manifest中的配置文件标识一致
                        channelName = String.valueOf(applicationInfo.metaData.get("APP_CHANNEL"));
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelName;
    }
}
